import Vuex from "vuex"
import Vue from 'vue'
import axios from 'axios'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        goodsList: []
    },
    mutations: {
        setGoodsList(state, newList) {
            state.goodsList = newList
        },
        controlck(state, val) {
            state.goodslist.forEach(item => item.goods_state = val)
        }
    },
    actions: {
        async asyncSetGoodsList(store) {
            //1.发送ajax请求
            const res = await axios({
                // method: "GET",
                url: "https://www.escook.cn/api/cart"
            })
            //2.后台响应的数据 commit到setGoodsList mutations
            store.commit('setGoodsList', res.data.list)
        }
    },
    // getters相当于vue中的computed计算属性
    getters: {
        totalCount(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count
                }
                return sum
            }, 0)
        },
        totalPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count * obj.goods_price
                }
                return sum
            }, 0)
        },
        isAll(state) {
            return state.goodsList.every(obj => obj.goods_state === true)
        }
    }
})

export default store